import * as XLSX from 'xlsx';
 

/**
 * // 导出工作表数据
 * @param {
 *  ws_data: [
*     ["姓名", "年龄", "职业"],
*     ["Alice", 28, "Engineer"],
*     ["Bob", 22, "Designer"]
*   ],
*   fileName: '导出文件名称'
 * }  
 */

const exportXlsxFile = function(ws_data, fileName){

  if(!ws_data || !fileName){
    throw new Error('缺少文件内容或者文件名称！')
  }


  // 创建工作簿
  const wb = XLSX.utils.book_new();  
  
  // 将数据转换为工作表
  const ws = XLSX.utils.aoa_to_sheet(ws_data);
  
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  
  // 生成Excel文件并导出（这里导出的是二进制字符串，可以用来下载文件）
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
  
  // 创建下载链接
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  
  // 下载文件
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
  const link = document.createElement('a');
  let fileName_all = `${fileName}.xlsx`
  if (link.download !== undefined) { // 支持下载属性
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName_all);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

export {
  exportXlsxFile
} 
